using System.Text;
using System.Text.Json;

namespace McpApi.TestClient
{
    /// <summary>
    /// MCP测试客户端 - 用于本地测试MCP协议
    /// </summary>
    public class MCPTestClient : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly string _serverUrl;
        private readonly JsonSerializerOptions _jsonOptions;

        public MCPTestClient(string serverUrl = "http://localhost:5000")
        {
            _httpClient = new HttpClient();
            _serverUrl = serverUrl;
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            };
        }

        /// <summary>
        /// 测试MCP协议完整流程
        /// </summary>
        public async Task RunTestAsync()
        {
            Console.WriteLine("=== MCP测试客户端 ===");
            Console.WriteLine($"服务器地址: {_serverUrl}");
            Console.WriteLine();

            try
            {
                // 1. 测试健康检查
                await TestHealthCheck();

                // 2. 测试初始化
                await TestInitialize();

                // 3. 测试工具列表
                await TestListTools();

                // 4. 测试工具调用
                await TestCallTool();

                Console.WriteLine("✅ 所有测试通过！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试健康检查
        /// </summary>
        private async Task TestHealthCheck()
        {
            Console.WriteLine("1. 测试健康检查...");

            var response = await _httpClient.GetAsync($"{_serverUrl}/api/mcp/health");
            var content = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"   状态码: {response.StatusCode}");
            Console.WriteLine($"   响应: {content}");
            Console.WriteLine();
        }

        /// <summary>
        /// 测试初始化
        /// </summary>
        private async Task TestInitialize()
        {
            Console.WriteLine("2. 测试MCP初始化...");

            var request = new
            {
                jsonrpc = "2.0",
                id = 1,
                method = "initialize",
                @params = new
                {
                    protocolVersion = "2024-11-05",
                    capabilities = new
                    {
                        tools = new { listChanged = false }
                    },
                    clientInfo = new
                    {
                        name = "MCP Test Client",
                        version = "1.0.0"
                    }
                }
            };

            var response = await SendMCPRequest(request);
            Console.WriteLine($"   初始化响应: {response}");
            Console.WriteLine();
        }

        /// <summary>
        /// 测试工具列表
        /// </summary>
        private async Task TestListTools()
        {
            Console.WriteLine("3. 测试获取工具列表...");

            var request = new
            {
                jsonrpc = "2.0",
                id = 2,
                method = "tools/list",
                @params = new { }
            };

            var response = await SendMCPRequest(request);
            Console.WriteLine($"   工具列表响应: {response}");
            Console.WriteLine();
        }

        /// <summary>
        /// 测试工具调用
        /// </summary>
        private async Task TestCallTool()
        {
            Console.WriteLine("4. 测试工具调用...");

            // 测试查询生产订单
            var request = new
            {
                jsonrpc = "2.0",
                id = 3,
                method = "tools/call",
                @params = new
                {
                    name = "query_production_orders",
                    arguments = new
                    {
                        orderId = "PO001",
                        status = "进行中"
                    }
                }
            };

            var response = await SendMCPRequest(request);
            Console.WriteLine($"   工具调用响应: {response}");
            Console.WriteLine();
        }

        /// <summary>
        /// 发送MCP请求
        /// </summary>
        private async Task<string> SendMCPRequest(object request)
        {
            var json = JsonSerializer.Serialize(request, _jsonOptions);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync($"{_serverUrl}/api/mcp", content);
            return await response.Content.ReadAsStringAsync();
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }


}
